package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

//对于publish的pid主键自增service
//借用Redis的自增长类型，实现MongoDB的主键自增长id
@Service
public class IdService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成主键自增长id
     *
     * @param type     看是推荐动态还是小视频推荐
     * @param objectId
     * @return
     */
    public Long createId(String type, String objectId) {
        type = StringUtils.upperCase(type);//将type转为大写
        //由于ObjectId id = Long pid一一对应，若再创建pid，就会导致多个pid对应ObjectId
        String hashKey = "TANHUA_HASH_ID_" + type;//用hash值查看ObjectId是否已存在
        //如果ObjectId已经存在，就返回对应的id,不会重新生成ObjectId
        if (redisTemplate.opsForHash().hasKey(hashKey, objectId)) {
            return Long.valueOf(redisTemplate.opsForHash().get(hashKey, objectId).toString());
        }

        String key = "TANHUA_ID_" + type;//type是根据推荐业务(圈子/小视频)创建Rediskey
        Long id = redisTemplate.opsForValue().increment(key);//主键自增

        //将生成的pid写入到hash表中
        redisTemplate.opsForHash().put(hashKey, objectId, id.toString());

        return id;
    }
}
